package com.dragon.connector.imServer.serverProcesser;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.dragon.common.util.JwtUtil;
import com.dragon.connector.imServer.protoBuilder.LoginResponseBuilder;
import com.dragon.connector.imServer.session.LocalSession;
import com.dragon.connector.imServer.session.service.SessionManger;
import com.dragon.protoJo.ProtoInstant;
import com.dragon.protoJo.bean.msg.ProtoMsg;
import com.dragon.protoJo.bean.msg.UserDTO;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class LoginProcesser extends AbstractServerProcesser{

    @Autowired
    LoginResponseBuilder loginResponceBuilder;
    @Autowired
    SessionManger sessionManger;

    @Override
    public ProtoMsg.HeadType op()
    {
        return ProtoMsg.HeadType.LOGIN_REQUEST;
    }

    @Override
    public Boolean action(LocalSession session,
                          ProtoMsg.Message proto)
    {
        // 取出token验证
        ProtoMsg.LoginRequest info = proto.getLoginRequest();

        String token = JwtUtil.validateToken(info.getToken());

        if(StrUtil.isBlank(token)){
            return false;
        }

        Map<String,String> map = JSON.parseObject(token,Map.class);
        String uid = MapUtil.get(map,"id",String.class);
        //List<String> groupIds = MapUtil.get(map,"groupIds",List.class);
        long seqNo = proto.getSequence();
        UserDTO user = UserDTO.fromMsg(info);
        user.setUserId(uid);

//        if(groupIds!=null){
//            user.setGroupIds(groupIds);
//        }
        //检查用户
        boolean isValidUser = checkUser(user);
        if (!isValidUser)
        {
            ProtoInstant.ResultCodeEnum resultcode =
                    ProtoInstant.ResultCodeEnum.NO_TOKEN;
            ProtoMsg.Message response =
                    loginResponceBuilder.loginResponce(resultcode, seqNo, "-1");
            //发送之后，断开连接
            session.writeAndClose(response);
            return false;
        }

        session.setUser(user);

        /**
         * 绑定session
         */
        session.bind();
        sessionManger.addLocalSession(session);

        /**
         * 绑定群聊
         */
//        if(groupIds != null){
//            sessionManger.addGroupSession(session);
//        }

        /**
         * 通知客户端：登录成功
         */

        ProtoInstant.ResultCodeEnum resultcode = ProtoInstant.ResultCodeEnum.SUCCESS;
        ProtoMsg.Message response =
                loginResponceBuilder.loginResponce(resultcode, seqNo, session.getSessionId());
        session.writeAndFlush(response);
        return true;
    }


    private boolean checkUser(UserDTO user)
    {
        //校验用户,比较耗时的操作,需要100 ms以上的时间
        //方法1：调用远程用户restfull 校验服务
        //方法2：调用数据库接口校验
//        List<ServerSession> l = sessionManger.getSessionsBy(user.getUserId());
//        if (null != l && l.size() > 0)
//        {
//            return false;
//        }
        return true;
    }

    /**
     * 登录接收tcp消息
     * @param ctx
     * @param proto
     * @return
     */
    @Override
    public Boolean actionTcp(ChannelHandlerContext ctx, ProtoMsg.Message proto) {
        return null;
    }
}
